'use strict'

// 引用模块（引用所需要的表）
let { User, Count, CountOption, Question, Questionnaire } = require('../models');
const auth = require('../utils/auth');

// let quesId;

// 显示加载首页界面
let index_fn = async (ctx, next) => {
    let username = ctx.session.userName;
    let obj={
        username:username
    }
    ctx.render("index.html",obj)
}

// 显示加载问卷案例界面
let work_fn = async (ctx, next) => {
    let userId = ctx.session.userId;
    
    // ctx.session=null;
    // console.log("用户id是" + userId);
    console.log(userId);


    let queForm = JSON.parse(JSON.stringify(await Questionnaire.findAll({
        where: {
            fromUserId: userId
        }
    })));

    let obj = {
        queForm: queForm
    }
    ctx.render('work.html', obj);
}

// 显示加载关于我们界面
let about_fn = async (ctx, next) => {
    ctx.render("about.html")
}

// 显示加载联系我们界面
let contact_fn = async (ctx, next) => {
    ctx.render("contact.html")
}

// 显示加载登录界面 /login在Sign_up下
let login_fn = async (ctx, next) => {
    ctx.render("./Sign_up/login.html")
}

// 显示加载注册界面 /register在Sign_up下
let register_fn = async (ctx, next) => {
    ctx.render("./Sign_up/register.html")
}

//设置界面
let work_single_fn = async (ctx, next) => {
    ctx.render("work-single.html")
}
//加载服务中心
let about_bz_fn = async (ctx, next) => {
    ctx.render("about_bz.html")
}

//==========================================================================================
//==========================================================================================


// 加载添加页
let add_fn = async (ctx, next) => {
    ctx.render('./add/add.html');
}

// 添加问卷页操作
let addDone_fn = async (ctx, next) => {
    let title = ctx.request.body.title || "";
    let presentation = ctx.request.body.presentation || "";
    let type = ctx.request.body.type || "";
    let fromUserId = ctx.session.userId;


    let ques = await Questionnaire.create({
        fromUserId: fromUserId,
        title: title,
        presentation: presentation,
        questionnaireType: type
    })

    let data = JSON.stringify(ques);

    let quforms = JSON.parse(JSON.stringify(await Questionnaire.findAll({
        where: {
            fromUserId: fromUserId,
            title: title,
            presentation: presentation,
            questionnaireType: type
        }
    })));

    let qusId;
    quforms.forEach(item => {
        qusId = item.id
    });

    ctx.body = { code: 200, data, msg: "填写成功啦！！！", id: qusId, type: type }
}

let addMassageStatistics_fn = async (ctx, next) => {
    let query = ctx.request.query;
    let id = query.id;
    console.log(id);
    if (id !== 0 && id !== undefined) {
        ctx.render('./add/addMessageStatistics.html');
    } else {
        ctx.render("./404.html")
    }
}

let addMassageStatisticsDone_fn = async (ctx, next) => {

}

// 加载添加统计分数问卷
let addMassageCount_fn = async (ctx, next) => {
    let query = ctx.request.query;
    let id = query.id;

    if (!isNaN(id)) {
        let queForm = JSON.parse(JSON.stringify(await Questionnaire.findAll({
            where: {
                id: id
            }
        })));
        if (queForm[0] !== undefined) {
            if (id != 0 && id !== undefined && id !== "") {
                let quenaire = JSON.parse(JSON.stringify(await Questionnaire.findAll({
                    where: {
                        id: id
                    }
                })));
                console.log(quenaire);
                let qneId;
                let qneTitle;
                let qnePresentation;
                let qneType;

                quenaire.forEach(item => {
                    qneId = item.id;
                    qneTitle = item.title;
                    qnePresentation = item.presentation;
                    qneType = item.questionnaireType;
                })

                let counts = JSON.parse(JSON.stringify(await Count.findAll({
                    where: {
                        fromQuestionnaireId: qneId
                    }
                })));

                let queIds = [];
                let queContents = [];
                counts.forEach(item => {
                    queIds.push(item.id);
                    queContents.push(item.countContent);
                });

                let countOptions = JSON.parse(JSON.stringify(await CountOption.findAll({
                    where: {
                        fromQuestionId: queIds
                    }
                })));

                let optIds = [];
                let optContents = [];
                let optTypes = [];

                countOptions.forEach(item => {
                    optIds.push(item.id);
                    optContents.push(item.optionContent);
                    optTypes.push(item.optionType);
                })

                counts.forEach(item => {
                    let opts = countOptions.filter(opt => {
                        return opt.fromQuestionId === item.id;
                    })[0];
                    // console.log("这是opts");
                    // console.log(opts.id);
                    // console.log(opts.optionContent);
                    // console.log(opts.optionType);

                    item.optId = opts.id;
                    item.optContents = opts.optionContent;
                    item.optTypes = opts.optionType;
                })
                console.log("底下是count");
                console.log(counts);
                console.log(counts[0]);
                let obj = {
                    qneTitle,
                    qnePresentation,
                    qneType,
                    counts,
                }
                ctx.render('./add/addMessageCount.html', obj);
            } else {
                ctx.render("./404.html")
            }
        } else {
            ctx.render("./404.html");
        }
    } else {
        ctx.render("./404.html");
    }
}

// 统计问卷添加输分题
let addScoreProblems_fn = async (ctx, next) => {
    let id = ctx.request.body.id || "";
    let type = 1;

    let counts = await Count.create({
        fromQuestionnaireId: id,
        countContent: "",
        countType: type
    })

    let data = JSON.stringify(counts);
    ctx.body = { code: 200, data, msg: "添加成功啦！！！" }

}

// 添加count选项
let addOptions_fn = async (ctx, next) => {
    let fromQuestionId = ctx.request.body.id || "";
    let optionContent = ctx.request.body.value || "";
    let optionType = ctx.request.body.type || "";

    let countOps = await CountOption.create({
        fromQuestionId: fromQuestionId,
        optionContent: optionContent,
        optionType: optionType
    })

    let data = JSON.stringify(countOps);
    ctx.body = { code: 200, data, msg: "成功" }
}

// 统计问卷添加选分题
let addSelectScore_fn = async (ctx, next) => {
    let id = ctx.request.body.id || "";
    let type = 2;

    let counts = await Count.create({
        fromQuestionnaireId: id,
        countContent: "",
        countType: type
    })


    let data = JSON.stringify(counts);
    ctx.body = { code: 200, data, msg: "添加成功啦！！！" }

}

// count提交
let countSubmit_fn = async (ctx, next) => {
    let subForm = ctx.request.body.subForm || "";
    let id = ctx.request.body.id || "";

    let subNameArr = [];
    let subValueArr = [];

    for (let sub in subForm) {
        subNameArr.push(sub);
        subValueArr.push(subForm[sub]);
    }

    let subType = [];
    let subId = [];

    for (let i = 0; i < subNameArr.length; i++) {
        let type = subNameArr[i].substring(0, 3);
        let id = subNameArr[i].slice(3);
        let value = subValueArr[i];
        subType.push(type);
        subId.push(id);
        if (type === "adq") {
            let addQues = await Count.update({
                countContent: value
            }, {
                where: {
                    id: id
                }
            });
        } else if (type === "ops") {
            let addOpts = await CountOption.update({
                optionContent: value
            }, {
                where: {
                    id: id
                }
            })
        }
    }
    ctx.body = { code: 200, msg: "添加成功啦！！！" }
}

// let countShowLoad_fn = async (ctx, next) => {
//     let id = ctx.request.body.id || "";
//     quesId=id;
// }

// 统计问卷展示页
let countShow_fn = async (ctx, next) => {
    let query = ctx.request.query;
    let id = query.id;

    if (!isNaN(id)) {

        let queForm = JSON.parse(JSON.stringify(await Questionnaire.findAll({
            where: {
                id: id
            }
        })));
        // console.log("看看");
        // console.log(queForm[0]);
        if (queForm[0] !== undefined) {
            if (id != 0 && id !== undefined && id !== "") {
                // console.log(id);
                if (id != null && id != "") {
                    let quenaire = JSON.parse(JSON.stringify(await Questionnaire.findAll({
                        where: {
                            id: id
                        }
                    })));
                    console.log(quenaire);
                    let qneId;
                    let qneTitle;
                    let qnePresentation;
                    let qneType;

                    quenaire.forEach(item => {
                        qneId = item.id;
                        qneTitle = item.title;
                        qnePresentation = item.presentation;
                        qneType = item.questionnaireType;
                    })

                    let counts = JSON.parse(JSON.stringify(await Count.findAll({
                        where: {
                            fromQuestionnaireId: qneId
                        }
                    })));

                    let queIds = [];
                    let queContents = [];
                    counts.forEach(item => {
                        queIds.push(item.id);
                        queContents.push(item.countContent);
                    });

                    let countOptions = JSON.parse(JSON.stringify(await CountOption.findAll({
                        where: {
                            fromQuestionId: queIds
                        }
                    })));

                    let optIds = [];
                    let optContents = [];
                    let optTypes = [];

                    countOptions.forEach(item => {
                        optIds.push(item.id);
                        optContents.push(item.optionContent);
                        optTypes.push(item.optionType);
                    })

                    counts.forEach(item => {
                        let opts = countOptions.filter(opt => {
                            return opt.fromQuestionId === item.id;
                        })[0];
                        // console.log("这是opts");
                        // console.log(opts.id);
                        // console.log(opts.optionContent);
                        // console.log(opts.optionType);

                        item.optId = opts.id;
                        item.optContents = opts.optionContent;
                        item.optTypes = opts.optionType;
                    })
                    // console.log("底下是count");
                    // console.log(counts);

                    let obj = {
                        qneTitle,
                        qnePresentation,
                        qneType,
                        counts,
                    }


                    ctx.render("./show/countShow.html", obj)
                } else {
                    console.log("你还没有添加题目");
                }
            } else {
                ctx.render("./404.html");
            }
        } else {
            ctx.render("./404.html");
        }
    } else {
        ctx.render("./404.html");
    }
}

// 统计问卷用户填表数据
let countShowSubmit_fn = async (ctx, next) => {
    let subForm = ctx.request.body.subForm || "";
    console.log(subForm);
    let subNameArr = [];
    let subValueArr = [];

    for (let sub in subForm) {
        subNameArr.push(sub);
        subValueArr.push(subForm[sub]);
    }

    let subType = [];
    let subId = [];

    let userId = ctx.session.userId;

    for (let i = 0; i < subNameArr.length; i++) {
        let type = subNameArr[i].substring(0, 3);
        let id = subNameArr[i].slice(3);
        let value = subValueArr[i];
        subType.push(type);
        subId.push(id);
        let showDemo = await CountShow.findOne({
            where: {
                fromUseId: userId,
                fromQuestionId: id,
            }
        });

        let u2Json = JSON.stringify(showDemo);
        console.log("打印");
        console.log(showDemo);
        console.log(u2Json);
        if (u2Json === "null") {
            console.log("11");
            let addOptions = await CountShow.create({
                fromUseId: userId,
                fromQuestionId: id,
                score: value
            })
        } else {

            let showDemoId = showDemo.id;

            console.log(showDemoId);
            let addOptions = await CountShow.update({
                score: value
            }, {
                where: {
                    id: showDemoId
                }
            })
        }
        let addOptions = await CountShow.create({
            fromUseId: userId,
            fromQuestionId: id,
            score: value
        })
    }

    ctx.body = { code: 200, msg: "提交成功啦！！！" }
    // console.log(subId);
    // console.log(subType);

}

let showSubmitOk_fn = async (ctx, next) => {
    let query = ctx.request.query;
    let id = query.id;
    console.log(id);
    if (!isNaN(id)) {
        let queForm = JSON.parse(JSON.stringify(await Questionnaire.findAll({
            where: {
                id: id
            }
        })));
        console.log("看看");
        console.log(queForm[0]);
        if (queForm[0] !== undefined) {
            if (id != 0 && id !== undefined && id !== "") {
                ctx.render("./show/showSubmitOk.html")
            } else {
                ctx.render("./404.html")
            }
        } else {
            ctx.render("./404.html");
        }
    } else {
        ctx.render("./404.html");
    }

}

let addSubmitOk_fn = async (ctx, next) => {
    let query = ctx.request.query;
    let id = query.id;
    console.log(id);
    if (!isNaN(id)) {
        let queForm = JSON.parse(JSON.stringify(await Questionnaire.findAll({
            where: {
                id: id
            }
        })));
        console.log("看看");
        console.log(queForm[0]);
        if (queForm[0] !== undefined) {
            if (id != 0 && id !== undefined && id !== "") {
                ctx.render("./add/addSubmitOk.html")
            } else {
                ctx.render("./404.html")
            }
        } else {
            ctx.render("./404.html")
        }
    } else {
        ctx.render("./404.html")
    }

}

let share_fn = async (ctx, next) => {

}

let cancel_fn = async (ctx, next) => {

}

let show_fn = async (ctx, next) => {
    ctx.render("./show.html")
    let userId = ctx.session.userId;
    let query = ctx.request.query;
    let id = Number(query.id);
    console.log(id);

    // console.log(queForm[0]);

    if (id != 0 && id !== undefined && id !== "") {
        if (!isNaN(id)) {
            // 返回id正确
            let quenaire = JSON.parse(JSON.stringify(await Questionnaire.findAll({
                where: {
                    id: id
                }
            })));
            if (quenaire[0] !== undefined) {

                let qneId;
                let qneTitle;
                let qnePresentation;
                let qneType;

                quenaire.forEach(item => {
                    qneId = item.id;
                    qneTitle = item.title;
                    qnePresentation = item.presentation;
                    qneType = item.questionnaireType;
                })
                console.log(qneId);
                console.log(qneTitle);
                console.log(qnePresentation);
                console.log(qneType);
                let counts = JSON.parse(JSON.stringify(await Count.findAll({
                    where: {
                        fromQuestionnaireId: qneId
                    }
                })));


                let queIds = [];
                let queContents = [];
                counts.forEach(item => {
                    queIds.push(item.id);
                    queContents.push(item.countContent);
                });

                console.log(queIds);

                // let counts = JSON.parse(JSON.stringify(await Count.findAll({
                //     where: {
                //         fromQuestionnaireId: queIds
                //     }
                // })));
                console.log("准备countshow");
                let countShows = JSON.parse(JSON.stringify(await CountShow.findAll({
                    where: {
                        fromQuestionId: queIds
                    }
                })));

                // console.log("底下是countShow");
                console.log(countShows);
                countShows.forEach(item => {
                    let questions = counts.filter(qus => {
                        return qus.id = item.fromQuestionId
                    })[0];

                    item.ShowContent = questions.countContent;
                });
                let ShowIds = [];
                let countScore = [];
                countShows.forEach(item => {
                    ShowIds.push(item.fromUseId);
                    countScore.push(item.score)
                })


                console.log("最后");
                counts.forEach(item => {
                    let shows = countShows.filter(show => {
                        return show.fromQuestionId === item.id;
                    })[0];
                    console.log(shows);
                    // console.log("这是opts");
                    // console.log(opts.id);
                    // console.log(opts.optionContent);
                    // console.log(opts.optionType);

                    item.ShowScore = shows.score;
                    item.ShowUserId = shows.fromUseId;
                    // item.optId = opts.id;
                    // item.optContents = opts.optionContent;
                    // item.optTypes = opts.optionType;
                })
                console.log("底下是count");
                console.log(counts);
                let ques = JSON.parse(JSON.stringify(await Questionnaire.findAll({
                    where: {
                        fromUserId: userId
                    }
                })));
                console.log(ques);
                let quesTitle = [];
                ques.forEach(item => {
                    quesTitle.push(item.title);
                })
                console.log(quesTitle);
                console.log(counts.ShowUserId);
                // let countUserId = [];
                // let countScore = [];
                // counts.forEach(item => {
                //     countUserId.push(item.ShowUserId);
                //     countScore.push(item.ShowScore);
                // })


                let showsScore = JSON.parse(JSON.stringify(await CountShow.findAll({
                    where: {
                        fromQuestionId: queIds
                    }
                })));

                console.log("分数");
                console.log(countScore);
                let countScoreAll = 0;
                for (let i = 0; i < countScore.length; i++) {
                    countScoreAll += Number(countScore[i]);
                }

                let users = JSON.parse(JSON.stringify(await User.findAll({
                    where: {
                        id: ShowIds
                    }
                })));
                console.log("下面用户表");
                console.log(users);

                let obj = {
                    users,
                    quesTitle,
                    counts,
                    countScoreAll,
                    countShows
                }
                ctx.render("./show.html", obj)
            } else {
                ctx.render("./404.html")
            }
        } else {
            // ctx.render("./show.html")
            ctx.render("./404.html")
        }
    } else {
        ctx.render("./404.html")
    }

}

let showDone_fn = async (ctx, next) => {
    console.log("ssds");
    let questionnaireId = ctx.request.body.questionnaireId || "";

    console.log(questionnaireId);
}


//==========================================================================================
//==========================================================================================


// let editMessageCount_fn = async (ctx, next) => {
//     ctx.render("./question/editMessageCount.html")
// }

//==========================================================================================
// 加载处理登录请求
let loginDone_fn = async (ctx, next) => {
    // 获取从前端传来的数据（用户信息）
    let uid = ctx.request.body.username.trim() || '';
    let pwd = ctx.request.body.password.trim() || '';

    let res = '';

    if (uid.length > 0 && pwd.length > 0) {
        let row = await User.findOne({
            where: {
                username: uid,
                password: pwd
            }
        });
        let u2Json = JSON.stringify(row);
        if (u2Json !== 'null') {
            ctx.session.userId = row.id;
            ctx.session.userName = row.username;
            res = { code: 200, msg: '登录成功' };
        } else {
            res = { code: 1000, msg: '用户名或密码错误，请确认后重试' };
        }

    } else {
        res = { code: 1000, msg: '用户名和密码不能为空' };
    }
    ctx.body = JSON.stringify(res);
};

// 加载处理注册请求
let registerDone_fn = async (ctx, next) => {
    // 获取从前端传来的数据（用户信息）
    let uid = ctx.request.body.username.trim() || '';
    let pwd = ctx.request.body.password.trim() || '';
    let confirmpwd = ctx.request.body.confirmpassword.trim() || '';

    let res = '';

    // 判断用户名、密码是否为空，为空则返回提示信息；不为空则尝试从数据库中查询是否有同名用户，如果没有，则创建用户；如果有，则返回提示信息；
    // 初步尝试then的玩法，出现了一些顺序问题（前端获取的返回数据为空的情况）
    if (uid.length > 0 && pwd.length > 0 && pwd === confirmpwd) {
        let row = await User.findOne({
            where: {
                username: uid
            }
        });
        let u2Json = JSON.stringify(row);
        if (u2Json === 'null') {
            let u1 = await User.create({
                username: uid,
                password: pwd
            });
            let u1Json = JSON.stringify(u1);
            if (u1Json !== 'null') {
                res = { code: 200, msg: '用户注册成功' };
            } else {
                res = { code: 1000, msg: '因为服务器或者网络原因，用户未注册成功' };
            }
        } else {
            res = { code: 1000, msg: '当前用户名已经注册，请确认后重试' };
        }
    } else {
        res = { code: 1000, msg: '用户名和密码不能为空，且两密码应该一致' };
        console.log(uid);
        console.log(pwd);
        console.log(confirmpwd);
    }
    // 返回消息
    ctx.body = JSON.stringify(res);
};
// 注销
let logout_fn = async (ctx, next) => {
    ctx.session = null;
    ctx.body = { code: 200, msg: '注销成功' };
}

//==========================================================================================
//首页 | 问卷案例 | 关于我们 | 联系我们 | 登录 | 注册跳转

module.exports = {
    "/": ["get", auth, index_fn],            //首页
    "/work": ['get', work_fn],                //个人中心
    "/about": ['get', about_fn],              //关于我们  
    "/contact": ['get', contact_fn],          //联系我们

    "/add": ["get", add_fn],
    "/addDone": ["post", addDone_fn],
    "/addMessageStatistics": ["get", addMassageStatistics_fn],
    "/addMessageStatisticsDone": ["post", addMassageStatisticsDone_fn],
    "/addMessageCount": ["get", addMassageCount_fn],
    "/addScoreProblems": ["post", addScoreProblems_fn],
    "/addOptions": ["post", addOptions_fn],
    "/addSelectScore": ["post", addSelectScore_fn],
    
    "/countSubmit": ["post", countSubmit_fn],
    "/countShow": ["get", countShow_fn],
    "/countShowSubmit": ["post", countShowSubmit_fn],
    "/showSubmitOk": ["get", showSubmitOk_fn],
    "/addSubmitOk": ["get", addSubmitOk_fn],
    "/show": ["get", auth, show_fn],
    "/showDone": ["post", showDone_fn],

    "/share": ["post", share_fn],        // 
    "/cancel": ["post", cancel_fn],      //
    '/logout': ['post', auth, logout_fn],    //注销
    "/login": ["get", auth, login_fn],       //登录
    "/register": ["get", register_fn],       //注册
    "/work-single": ["get", work_single_fn],        //设置
    "/about_bz": ["get", about_bz_fn],              //服务中心
    '/loginDone': ['post', loginDone_fn],           //处理登录请求
    '/registerDone': ['post', registerDone_fn],     //处理注册请求
    
    // "/editMessageCount":['get',editMessageCount_fn],
}